package splash.core.execution;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

import java.net.ServerSocket;
import java.net.Socket;

public class ImageThread implements Runnable{

        private ServerSocket s;
        private BufferedImage resizedImage;

        public ImageThread(ServerSocket ss, BufferedImage bi)
        {
            this.s = ss;
            this.resizedImage = bi;
        }

        private ImageThread()
        {
        }

        public void run()
        {

            Socket sck = null;
            InputStream is = null;
            OutputStream os = null;

            try
            {
                s.setSoTimeout(20000);
                sck = s.accept();
                os = sck.getOutputStream();
                is = sck.getInputStream();
            }
            catch(IOException e)
            {
                e.printStackTrace();
                close();
                return;
            }

            try
            {
                ImageIO.write(resizedImage, "jpg", os);
            }
            catch(IOException e)
            {}

            try
            {
                is.close();
                os.close();
                sck.close();
            }
            catch(Exception e)
            {
            }
        }

        private void close()
        {
            try
            {
                s.close();
            }
            catch(IOException ioe)
            {
                s = null;
                System.gc();
            }
        }
}
